package com.promis.okhttp;

import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * Created by jidanbo on 2018/1/31.
 */

public abstract class ProgressRequestListener {

    private static final int REQUEST_UPDATE = 0x01;

    private final WeakReference<ProgressRequestListener> progressRequestListenerWeakReference;
    private Handler handler;

    public ProgressRequestListener() {
        progressRequestListenerWeakReference = new WeakReference<>(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case REQUEST_UPDATE:
                        ProgressRequestListener uiProgressResponseListener = progressRequestListenerWeakReference.get();
                        if (uiProgressResponseListener != null) {
                            //获得进度实体类
                            ProgressModel progressModel = (ProgressModel) msg.obj;
                            //回调抽象方法
                            onRequestProgress(progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
                        }
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };
    }

    void setRequestUpdate(long bytesWritten, long contentLength, boolean done) {
        Message message = Message.obtain();
        message.obj = new ProgressModel(bytesWritten, contentLength, done);
        message.what = REQUEST_UPDATE;
        handler.sendMessage(message);
    }

    public abstract void onRequestProgress(long bytesWritten, long contentLength, boolean done);
}
